using IQIGame.Onigao.Framework;
using IQIGame.Onigao.GamePlay;
using System.Collections.Generic;

namespace IQIGame.Onigao.Logic
{
    public static class LevelServiceModule
    {
        /// <summary>
        /// 执行一个ServiceUnit
        /// </summary>
        /// <param name="player"></param>
        /// <param name="unit">服务单元</param>
        /// <param name="needBreak">是否要立即打断后续服务单元</param>
        /// <returns>成功生效的执行个数</returns>
        public static int ExecUnit(LevelPlayer player, LevelServiceUnit unit, bool isEntityService, out bool needBreak)
        {
            if (unit.disabled)
            {
                needBreak = false;
                return 0;
            }
            int successExecCount;
            bool isConditionOK = unit.CheckCondition(player);
#if UNITY_EDITOR
            LevelEntity entity = unit.host as LevelEntity;
            string entityName = entity == null ? "无" : (entity.entityConfig != null && entity.entityConfig.infoCid != 0 ? TableCenter.levelEntityInfo.Get(entity.entityConfig.infoCid)?.Name : entity.entityConfig?.id.ToString());
            LogicLog.Log($"执行服务 cid: {unit.serviceId}，所属实体：{entityName}，单元index：{unit.index}，满足条件？：{isConditionOK}");
#endif
            ServiceBreakType breakType = unit.breakType;
            if (unit.delay <= 0)
            {
                successExecCount = unit.Execute(player, isConditionOK);
            }
            else
            {
                player.level.delayServiceMgr.AddDelayService(player, unit, isConditionOK ? DelayServiceCondition.True : DelayServiceCondition.False, !isEntityService, true);
                successExecCount = unit.GetCanExecCount(isConditionOK);
            }

            if ((breakType == ServiceBreakType.OnSucceeded && isConditionOK)
                || (breakType == ServiceBreakType.OnFailed && !isConditionOK))
            {
                needBreak = true;
            }
            else
            {
                needBreak = false;
            }
            return successExecCount;
        }

        /// <summary>
        /// 触发不绑定在实体身上的服务，如气泡，对话等
        /// </summary>
        /// <param name="player"></param>
        /// <param name="entity">与服务关联的实体，可能为空</param>
        /// <param name="services"></param>
        public static void TriggerSystemServices(LevelRegion region, LevelPlayer player, LevelEntity entity, IReadOnlyList<int> services)
        {
            int count = 0;
            for (int i = 0; i < services.Count; i++)
            {
                int serviceCid = services[i];
                bool hasCfg = region.gameplayConfig.services.TryGetValue(serviceCid, out var cfg);
#if UNITY_EDITOR
                if (!hasCfg)
                {
                    LogicLog.LogError($"关卡配置里找不到服务. Service id: {serviceCid}");
                    return;
                }
#endif
                for (int j = 0; j < cfg.serviceUnits.Count; j++)
                {
                    var unitConfig = cfg.serviceUnits[j];
                    LevelServiceUnit unit = ClassPool.Get<LevelServiceUnit>();
                    unit.Init(cfg.id, i, unitConfig, entity);
                    count += ExecUnit(player, unit, false, out bool needBreak);
                    ClassPool.Put(unit);
                    if (needBreak)
                    {
                        break;
                    }
                }
            }

            LogicLog.Log($"尝试触发独立服务，成功运行的执行数量：{count}");
        }

        public static void TriggerSystemServices(LogicPlayer logicPlayer, IReadOnlyList<int> services)
        {
            LevelPlayer levelPlayer = logicPlayer.levelPlayer;
            if (levelPlayer == null || levelPlayer.region == null) return;
            TriggerSystemServices(levelPlayer.region, levelPlayer, null, services);
        }

        /// <summary>
        /// 主动点击交互按钮交互触发服务，如果正常触发失败，则触发“零服务”触发器（一般策划会配置随便说一句话）
        /// </summary>
        /// <param name="player"></param>
        /// <param name="entity"></param>
        /// <param name="triggerType"></param>
        /// <param name="dynamicParam"></param>
        /// <returns>是否有任意执行成功生效</returns>
        public static bool TriggerInteractiveEntity(LevelPlayer player, LevelEntity entity, ServiceTriggerType triggerType, object dynamicParam = null, TrigValueTypeParam valueTypeParam = default)
        {
            if (entity.isAvailable)
            {
                bool hasSuccess = entity.TryTriggerService(player, triggerType, dynamicParam, valueTypeParam);
                if (!hasSuccess) //交互触发失败，触发“零服务”触发器
                {
                    hasSuccess = entity.TryTriggerService(player, ServiceTriggerType.NoServiceTiggeredWhenInteract, dynamicParam, valueTypeParam);
                }
                return hasSuccess;
            }
            return false;
        }
    }
}
